<template>
  <div class="generator-wrapper">
    <SearchForm @queryList="handleQueryList" />
    <a-table
      rowKey="id"
      bordered
      :loading="loading"
      :rowSelection="rowSelection"
      :columns="displayFieldList"
      :dataSource="dataSource"
      :scroll="tableProps.scroll"
    >
      <template #bodyCell="{ column }">
        <template
          v-if="column.key === 'action' || column.dataIndex === 'action'"
        >
          <a-space>
            <a> 编辑 </a>
            <a> 详情 </a>
            <a> 删除 </a>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from "vue";
import { storeToRefs } from "pinia";
import { useTableStore } from "@/store/table";

import SearchForm from "./SearchForm/index.vue";

const store = useTableStore();
const { tableProps, fieldList } = storeToRefs(store);

const loading = ref(false);
const dataSource = ref([]);

const displayFieldList = computed(() => {
  return fieldList.value.map((column, index) => {
    return {
      ...column,
      customHeaderCell() {
        return {
          onClick() {
            store.setCurrentField(fieldList.value[index]);
          },
        };
      },
    };
  });
});

const rowSelectionOption = ref({
  selectedRowKeys: [],
  selectRows: [],
  onChange: (selectedRowKeys, selectedRows) => {
    rowSelectionOption.value.selectedRowKeys = selectedRowKeys;
    rowSelectionOption.value.selectedRows = selectedRows;
  },
});

const rowSelection = computed(() =>
  tableProps.value.rowSelectionType
    ? {
        type: tableProps.value.rowSelectionType,
        ...rowSelectionOption.value,
      }
    : null
);

async function fetchData(searchForm = {}) {
  if (fieldList.value.length > 0) {
    loading.value = true;
    const response = await fetch("/mock/list", {
      method: "POST",
      body: JSON.stringify({
        searchForm,
        fieldList: fieldList.value,
      }),
    });
    const res = await response.json();
    setTimeout(() => {
      loading.value = false;
      dataSource.value = res.data.records
    }, 300);
  }
}

function handleQueryList(searchForm) {
  fetchData(searchForm);
}

watch(
  () => fieldList.value,
  () => {
    fetchData();
  }
);

onMounted(() => {
  fetchData();
});
</script>

<style lang="less" scoped>
:deep(.ant-table-thead .ant-table-cell) {
  cursor: pointer;
}
.generator-wrapper {
  box-sizing: border-box;
  padding: 15px;
  background: #fff;
  height: 100%;
}
</style>
